<?php

namespace app\admin\controller\business;

use app\common\controller\Backend;

/**
 * 
 */
class Highsea extends Backend
{
    // 快速查询，搜索指定的哪些字段
    protected $searchFields = 'business.id,nickname,source.name';
    /**
     * 当前控制器下的一个模型属性
     */
    protected $model = null;

    // 初始化
    public function _initialize()
    {
        parent::_initialize();

        // 全局用户模型
        $this->BusinessModel = model('Business.Business');

        // 回访表
        $this->VisitModel = model('Business.Visit');

        $this->AdminModel = model('Admin');

        $this->ReceiveModel = model('Business.Receive');

        $this->Adminlist = $this->AdminModel->select();

        $Admindata = [];

        foreach ($this->Adminlist as $k => &$v) {

            $Admindata[$v['id']] = $v['username'];
        }
        $this->view->assign('Admindata', $Admindata);
    }

    // 首页
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            // 此处将筛选请求中有争议的字段"id"指定为tableA中的id
            $this->changeWhereName("id", "business.id");

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->BusinessModel
                ->with('source')
                ->where($where)
                ->where('adminid', 'NULL')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();  //查询总数

            $list = $this->BusinessModel
                ->with('source')
                ->where($where)
                ->where('adminid', 'NULL')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();  //查询数据

            foreach ($list as $item) {
                $visit = $this->VisitModel->where('busid', $item['id'])->order('id DESC')->find();
                $item['visit'] =  $visit;
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    // 分配
    public function recovery($ids = null)
    {

        $ids = !empty($ids) ?  explode(',', $ids) : [];
        $row = $this->BusinessModel->all($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
            exit;
        }

        $this->assign("row", $row);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $list = [];
            $businesslist = [];
            foreach ($row as $value) {

                $list[] = [
                    'applyid' => $params['adminid'],
                    'status' => 'allot',
                    'busid' => $value['id']
                ];

                $businesslist[] = [
                    'id' => $value['id'],
                    'adminid' => $params['adminid']
                ];
            }

            $this->BusinessModel->startTrans();
            $this->ReceiveModel->startTrans();

            // 更新客户表
            $Businessres = $this->BusinessModel->saveAll($businesslist);

            if ($Businessres === FALSE) {
                $this->BusinessModel->rollback();
                $this->error($this->BusinessModel->getError());
            }
            // 插入领取表
            $Receiveres = $this->ReceiveModel->saveAll($list);

            if ($Receiveres === FALSE) {
                $this->BusinessModel->rollback();
                $this->ReceiveModel->rollback();
                $this->error($this->ReceiveModel->getError());
            }

            if ($Receiveres === FALSE || $Businessres === FALSE) {
                $this->BusinessModel->rollback();
                $this->ReceiveModel->rollback();
                $this->error('分配失败');
            } else {
                $this->BusinessModel->commit();
                $this->ReceiveModel->commit();
                $this->success('分配成功');
            }
        }

        return $this->view->fetch();
    }

    // 领取
    public function apply($ids = null)
    {
        $ids = !empty($ids) ?  explode(',', $ids) : [];
        $row = $this->BusinessModel->all($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
            exit;
        }

        $list = [];
        $businesslist = [];
        foreach ($row as $value) {

            $list[] = [
                'applyid' => $this->auth->id,
                'status' => 'apply',
                'busid' => $value['id']
            ];

            $businesslist[] = [
                'id' => $value['id'],
                'adminid' => $this->auth->id
            ];
        }

        $this->BusinessModel->startTrans();
        $this->ReceiveModel->startTrans();

        // 更新客户表
        $Businessres = $this->BusinessModel->saveAll($businesslist);

        if ($Businessres === FALSE) {
            $this->BusinessModel->rollback();
            $this->error($this->BusinessModel->getError());
        }
        // 插入领取表
        $Receiveres = $this->ReceiveModel->saveAll($list);

        if ($Receiveres === FALSE) {
            $this->BusinessModel->rollback();
            $this->ReceiveModel->rollback();
            $this->error($this->ReceiveModel->getError());
        }

        if ($Receiveres === FALSE || $Businessres === FALSE) {
            $this->BusinessModel->rollback();
            $this->ReceiveModel->rollback();
            $this->error('申请失败');
        } else {
            $this->BusinessModel->commit();
            $this->ReceiveModel->commit();
            $this->success('申请成功');
        }
    }

    // 详情
    public function detail($ids = null)
    {
        $ids = $ids ?  $ids : 0;

        // 客户详情
        $row = $this->BusinessModel->with('source')->where('adminid', 'NULL')->find($ids);
     
        $this->assign([
            
            'row' => $row
        ]);


        return $this->view->fetch();
    }


    // 删除
    public function del($ids = null)
    {
        $ids = !empty($ids) ?  explode(',', $ids) : [];

        $row = $this->BusinessModel->column('id');

        foreach ($ids as $item) {
            if (!in_array($item, $row)) {
                $this->error(__('没有找到该用户'));
                exit;
            }
        }

        $result = $this->BusinessModel->destroy($ids);

        if ($result === false) {
            $this->error($this->BusinessModel->getError());
            exit;
        }

        $this->success();
        exit;
    }
}
